package com.distribute.application.api.rest.delivery;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.domain.OrderItem;
import com.distribute.application.api.BaseApiController;
import com.distribute.application.api.utils.Arith;
import com.distribute.application.api.utils.mobile.MobileCodeUtil;
import com.distribute.framework.core.lang.Protocol;
import com.distribute.framework.core.lang.title;
import com.distribute.framework.core.web.helper.Utils;
import com.distribute.framework.model.Account;
import com.distribute.framework.model.Agent;
import com.distribute.framework.model.BindingDistributor;
import com.distribute.framework.model.Commodity;
import com.distribute.framework.model.Configur;
import com.distribute.framework.model.Coupon;
import com.distribute.framework.model.DirectOrder;
import com.distribute.framework.model.Distributor;
import com.distribute.framework.model.DistributorIncome;
import com.distribute.framework.model.IncomeRecord;
import com.distribute.framework.model.Member;
import com.distribute.framework.model.OrderDetails;
import com.distribute.framework.model.Parameter;
import com.distribute.framework.model.Region;
import com.distribute.framework.model.TbBalanceStatistics;
import com.distribute.framework.model.TbJxsh;
import com.distribute.framework.model.TbJxshIncome;
import com.distribute.framework.model.TbMsg;
import com.distribute.framework.model.TbOrderInvoies;
import com.distribute.framework.model.TbPartnerIncome;
import com.distribute.framework.model.TbPartners;

@RestController(value="api.DeliveryOrderController")
public class DeliveryOrderController  extends BaseApiController{
	/**
	 * 配送商获取订单列表
	 * @param id
	 * @return
	 */
	@RequestMapping("/api/delivery/deliveryOrders.do")
	public @title("配送商获取订单列表") Protocol deliveryOrders(
			@title("页码") Integer pageNo
			,@title("个数") Integer pageSize
			,@title("订单类型") Short type
			
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (type==(short)1) {
			type=(short)2;
		}else if (type==(short)2) {
			type=(short)3;
		}else if (type==(short)3) {
			type=(short)4;
		}else if (type==(short)4) {
			type=(short)5;
		}
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		Distributor distributor=Distributor.where.member(member.getId()).get();
		
		DirectOrder.M where = DirectOrder.where.distributor(distributor.getId()).sType((short)1);
		if(type!=(short)0){
			where.status(type);
		}else {
			where.statusIn("2,3,4,5");
		}
		protocol.setPage(where.page(Utils.or(pageNo,0), Utils.or(pageSize,20)), new Protocol.BeanFormat<DirectOrder>(){
			@Override
			public Map format(DirectOrder t) {
				Map json = t.toJSON();
				List<OrderDetails> orderDetails=OrderDetails.where.orders(t.getId()).list(-1);
				Member member=Member.where.uid(t.getMember()).get();
				json.put("user", member.toJSON());
				double zyj=0.0;
				List<Map<String, Object>> list=new ArrayList<Map<String,Object>>();
				if (orderDetails.size()>0) {
					for (OrderDetails oDetails : orderDetails) {
						Map<String, Object> map=new HashMap<String, Object>();
						map.put("id", oDetails.getId());
						map.put("name", oDetails.getName());
						map.put("orders", oDetails.getOrders());
						map.put("goodsNumber", oDetails.getGoodsNumber());
						map.put("img", oDetails.getImg());
						map.put("price", oDetails.getPrice());
						map.put("number", oDetails.getNumber());
						map.put("attributes", oDetails.getAttributes());
						if (t.getOrderType()==(short)1) {
							Parameter parameter=Parameter.where.merchant(t.getMerchant()).get();
							JSONArray yelistArray=JSON.parseArray(t.getUseProductVouchers());
							double aa=0.0;
							if (t.getCoupon()!=null) {
								Coupon coupon=Coupon.where.id(t.getCoupon()).get();
								if (coupon!=null&&oDetails.getGoodsNumber().toString().equals(coupon.getCommodity().toString())) {
									aa=aa+oDetails.getPrice()*(oDetails.getNumber()-1)*(coupon.getDiscount()/10)*parameter.getpPsYj();
								}else {
									if (yelistArray!=null&&yelistArray.size()>0) {
										for(int i=0;i<yelistArray.size();i++) {
											JSONObject jObject=yelistArray.getJSONObject(i);
											Long jidLong=jObject.getLong("commodity");
											if (jidLong!=null) {
												if (oDetails.getGoodsNumber().toString().equals(jidLong.toString())) {
													System.out.println("aa使用余额"+aa);
													 aa=aa+oDetails.getPrice()*jObject.getInteger("count")*0.7*parameter.getpPsYj()+(oDetails.getNumber()-jObject.getInteger("count"))*oDetails.getPrice()*parameter.getpPsYj();
												}else {
													aa=aa+oDetails.getPrice()*oDetails.getNumber()*(coupon.getDiscount()/10)*parameter.getpPsYj();
												}
											  }
											}
									}	
								}
							}
							map.put("distributorIncome", Arith.round(aa, 2));
							zyj=zyj+aa;
						}else {
							zyj=zyj+oDetails.getDistributorIncome();
							map.put("distributorIncome", Arith.round(oDetails.getDistributorIncome(), 2));
						}
						map.put("updateTime", oDetails.getUpdateTime$());
						map.put("addTime", oDetails.getAddTime$());
						map.put("status", oDetails.getStatus());
						list.add(map);
						
					}
				}
				json.put("distributorIncome", t.getOrderType()==(short)2?t.getDistributorIncome():Arith.round(zyj, 2));
				json.put("child", list);
				return json;
			}
		});
		return protocol;
	}
	
	/**
	 * 配送商同意接单
	 * @param id
	 * @return
	 */
	@RequestMapping("/api/delivery/agreeReceiptOrders.do")
	public @title("配送商同意接单") Protocol agreeReceiptOrders(
			@title("订单ID") Long orderId
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		Distributor distributor=Distributor.where.member(member.getId()).get();
		DirectOrder order = DirectOrder.where.id(orderId).distributor(distributor.getId()).get();
		    if (order==null) {
		    	protocol.set("type", 2);
		    	protocol.set("msg", "此订单已不存在");
		    	return protocol;
			}else {
				order.distributor(distributor.getId());
				order.distributorName(distributor.getName());
				    order.setStatus((short)3);//待收货
				    order.setGetOrderTime(new Date());
		            order.update();
		            Parameter parameter=Parameter.where.merchant(order.getMerchant()).get();
		        	List<OrderDetails> orderDetailss=OrderDetails.where.orders(order.getId()).list(100);
		        	double gj=0.0;
					if (orderDetailss.size()>0) {
						for (OrderDetails orderDetails : orderDetailss) {
							gj=gj+orderDetails.getDistributorIncome();
						}
					}
			        DistributorIncome distributorIncome=new DistributorIncome(
			        		order.getMerchant()//品牌商 [非空]
			        		,order.getMember()//下单人
			        	 	,distributor.getId()//配送商 [非空]
			        	 	,order.getId()//所属订单 [非空]
			        	 	,order.getOrderType()//订单类别 [非空]
			        	 	,order.getOrderType()==(short)2?order.getDistributorIncome():Arith.paytype(order.getTotalSum(), order.getDispatFee(), order.getDx(), parameter.getpPsYj(),order.getCouponFree())//总收益 [非空]
			        	 	,(short)1//收益状态 [非空]
			        	 	,new Date()//修改时间 [非空]
			        	 	,new Date()//添加时间 [非空]
			        	 	,(short)1//状态 [非空]
			        		);
			        distributorIncome.save();
			        TbOrderInvoies orderInvoies=TbOrderInvoies.where.tboiOrderNumber(order.getId()).get();
			        if (orderInvoies!=null) {
						orderInvoies.setTboiPsSy(Arith.paytype(order.getTotalSum(), order.getDispatFee(), order.getDx(), parameter.getpPsYj(),order.getCouponFree()));
						orderInvoies.update();
					}
			        BindingDistributor bindingDistributor=BindingDistributor.where.merchant(order.getMerchant()).distributor(distributor).get();
			        if (bindingDistributor!=null) {
						if (bindingDistributor.getBindingdJxsh()!=null) {
							TbJxsh jxs=TbJxsh.where.tbjId(bindingDistributor.getBindingdJxsh()).get();
							if (jxs!=null) {
								order.setJxs(jxs.getTbjName());
								order.update();
							}
							orderInvoies.setTboiJxsSy(Arith.round(Arith.mul(Arith.sub(order.getTotalSum(), order.getDispatFee()), parameter.getpJxshYj()), 2));
							orderInvoies.update();
						}
					}
			        MobileCodeUtil.sendTextPsJieDan(order.getReceivingTelephoneNumber(), order.getNo(), distributor.getName());
			        protocol.set("type", 1);
			    	protocol.set("msg", "接单成功");
			    	return protocol;
			}
	}
	/**
	 * 配送商订单退回总部
	 * @param id
	 * @return
	 */
	@RequestMapping("/api/delivery/returnHead.do")
	public @title("配送商订单退回总部") Protocol returnHead(
			@title("订单ID") Long orderId
			
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		Distributor distributor=Distributor.where.member(member.getId()).get();
		DirectOrder order = DirectOrder.where.id(orderId).distributor(distributor.getId()).get();
		    if (order==null) {
		    	protocol.set("type", 2);
		    	protocol.set("msg", "此订单已不存在");
		    	return protocol;
			}else {
				order.distributorIncome(0.0);
				order.dispatFee(0.0);
				  order.setDistributionMode((short)2);
				  order.setDistributor(null);
					order.distributorName("");
				  order.setsType((short)2);
		          order.update();
			        protocol.set("type", 1);
			    	protocol.set("msg", "订单已退回至总部");
			    	return protocol;
			}
	}
	/**
	 * 配送商拒绝退款
	 * @param id
	 * @return
	 */
	@RequestMapping("/api/delivery/ditrutorRefundment.do")
	public @title("配送商拒绝退款") Protocol ditrutorRefundment(
			@title("订单ID") Long orderId,
			@title("拒绝理由") String content
			
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		Distributor distributor=Distributor.where.member(member.getId()).get();
		DirectOrder order = DirectOrder.where.id(orderId).distributor(distributor.getId()).get();
		    if (order==null) {
		    	protocol.set("type", 2);
		    	protocol.set("msg", "此订单已不存在");
		    	return protocol;
			}else {
				order.setRefundStatus((short)3);
				order.setRefuseRefund(content);
				order.update();
			        protocol.set("type", 1);
			    	protocol.set("msg", "拒绝成功");
			    	return protocol;
			}
	}
	/**
	 * 配送商同意退款
	 * @param id
	 * @return
	 */
	@RequestMapping("/api/delivery/disAgreeTorefund.do")
	public @title("配送商同意退款") Protocol disAgreeTorefund(
			@title("订单ID") Long orderId
			
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		Distributor distributor=Distributor.where.member(member.getId()).get();
		DirectOrder order = DirectOrder.where.id(orderId).distributor(distributor.getId()).get();
		    if (order==null) {
		    	protocol.set("type", 2);
		    	protocol.set("msg", "此订单已不存在");
		    	return protocol;
			}else {
				order.setRefundStatus((short)2);
				List<DistributorIncome> distributorIncomes=DistributorIncome.where.directOrder(order.getId()).distributor(distributor.getId()).list(1);
				if (distributorIncomes.size()>0) {
					order.setStatus((short)3);//已接单了的
				}else {
					order.setStatus((short)2);//未接单的
				}
				order.update();
			        protocol.set("type", 1);
			    	protocol.set("msg", "处理成功!请尽快进行退款");
			    	return protocol;
			}
	}
	/**
	 * 配送商扫码核销订单
	 * @param id
	 * @return
	 */
	@RequestMapping("/api/delivery/saoHeOrder.do")
	public @title("配送商扫码核销订单") Protocol saoHeOrder(
			@title("码") String result
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		Distributor distributor2=Distributor.where.member(member.getId()).get();
		DirectOrder order = DirectOrder.where.no(result).distributor(distributor2.getId()).get();
		    if (order==null) {
		    	protocol.set("type", 2);
		    	protocol.set("msg", "此订单已不存在");
		    	return protocol;
			}else {
				if (order.getOrderType()==1) {
					if (order.getUseProductVouchers()!=null&&order.getUseProductVouchers().equals("")) {
						JSONArray daArray=JSONArray.parseArray(order.getUseProductVouchers());
						for (int i = 0; i < daArray.size(); i++) {
							JSONObject jsonObject=daArray.getJSONObject(i);
							TbBalanceStatistics balanceStatistics=TbBalanceStatistics.where.tbbsBrand(order.getMerchant()).get();
							if (balanceStatistics!=null) {
								balanceStatistics.setTbbsNowMonthBuy(balanceStatistics.getTbbsNowMonthBuy()+Integer.valueOf(jsonObject.getInteger("count")));
								balanceStatistics.setTbbsNowMonthSurplus(balanceStatistics.getTbbsNowMonthSurplus()+Integer.valueOf(jsonObject.getInteger("count")));
								balanceStatistics.update();
							}else {
								TbBalanceStatistics statistics=new TbBalanceStatistics(
										order.getMerchant()//品牌
									 	,0//上月余量
									 	,Integer.valueOf(jsonObject.getInteger("count"))//本月购量
									 	,0//本月兑换
									 	,Integer.valueOf(jsonObject.getInteger("count"))//本月剩余
									 	,new Date()//修改时间
										);
								statistics.save();
							}
						}
					}
				}
				List<OrderDetails> orderDetailss=OrderDetails.where.orders(order.getId()).list(100);
				if (orderDetailss.size()>0) {
					for (OrderDetails orderDetails : orderDetailss) {
						Commodity commodity=Commodity.where.id(orderDetails.getGoodsNumber()).get();
						commodity.setSaleVol(commodity.getSaleVol()+orderDetails.getNumber());
						commodity.setRaleVol(commodity.getRaleVol()+orderDetails.getNumber());
						commodity.update();
						if (order.getOrderType()==2) {
							TbBalanceStatistics balanceStatistics=TbBalanceStatistics.where.tbbsBrand(order.getMerchant()).get();
							if (balanceStatistics!=null) {
								balanceStatistics.setTbbsNowMonthBuy(balanceStatistics.getTbbsNowMonthBuy()+orderDetails.getNumber());
								balanceStatistics.setTbbsNowMonthSurplus(balanceStatistics.getTbbsNowMonthSurplus()+orderDetails.getNumber());
								balanceStatistics.update();
							}else {
								TbBalanceStatistics statistics=new TbBalanceStatistics(
										order.getMerchant()//品牌
									 	,0//上月余量
									 	,orderDetails.getNumber()//本月购量
									 	,0//本月兑换
									 	,orderDetails.getNumber()//本月剩余
									 	,new Date()//修改时间
										);
								statistics.save();
							}
						}
					}
				}
				order.setStatus((short)4);//订单改为已收货
				order.update();
				//查看配送商
				List<IncomeRecord> incomeRecords=IncomeRecord.where.orderNumber(order.getNo()).list(100);
				for (IncomeRecord incomeRecord : incomeRecords) {
					if (incomeRecord.getEndStatus()==(short)1) {
							Account tAccount=Account.where.member(incomeRecord.getBeneficiary()).get();
							if (tAccount!=null) {
								tAccount.setMoney(Arith.round(Arith.add(tAccount.getMoney(), incomeRecord.getIncome()), 2));//直接代理奖励
								 tAccount.update();
								 incomeRecord.setEndStatus((short)2);
								 incomeRecord.update();
								 TbMsg msg=new TbMsg(
										 incomeRecord.getBeneficiary()//会员
											 	,"您获得收益:"+incomeRecord.getIncome()//内容
											 	,new Date()//时间
												);
										msg.save();
							}
					}
				}
				 Parameter parameter=Parameter.where.merchant(order.getMerchant()).get();
				 Configur configur=Configur.where.status((short)1).get();
				 TbOrderInvoies orderInvoies=new TbOrderInvoies(
						    order.getNo()//订单编号
						 	,order.getOrderType()//来源
						 	,order.getMerchant()
						 	,order.getMember()//购买人
						 	,order.getTotalSum()//订单总金额
						 	,order.getActualPay()//实际支付金额
						 	,order.getProductFree()//余额抵扣金额
						 	,order.getCouponFree()//优惠卷抵扣金额
						 	,Arith.round(Arith.mul(Arith.sub(order.getTotalSum(), order.getDispatFee()), configur.getProfitRatio()), 2)//平台收益
						 	,0.0//普通间接收益
						 	,0.0//普通直接收益
						 	,0.0//代理间接收益
						 	,0.0//代理直接收益
						 	,0.0//合伙人收益
						 	,0.0//配送商收益
						 	,0.0//经销商收益
						 	,0.0
						 	,new Date()//添加时间
						 );
				    orderInvoies=orderInvoies.save();
				    if (member.gettTop()!=null&&!member.gettTop().equals("")) {
				    	Agent agent=Agent.where.member(Long.parseLong(member.gettTop())).merchant(order.getMerchant()).get();
				    	if (agent!=null) {
				    		orderInvoies.setTboiDlZj(Arith.round(Arith.mul(Arith.sub(order.getActualPay(), order.getDispatFee()), parameter.getpDlZj()), 2));
						}else {
							orderInvoies.setTboiPtZj(Arith.round(Arith.mul(Arith.sub(order.getActualPay(), order.getDispatFee()), parameter.getpPtZj()), 2));
						}
					}
				    if (member.gettToptop()!=null&&!member.gettToptop().equals("")) {
				    	Agent agent=Agent.where.member(Long.parseLong(member.gettToptop())).merchant(order.getMerchant()).get();
				    	if (agent!=null) {
				    		orderInvoies.setTboiDlJj(Arith.round(Arith.mul(Arith.sub(order.getActualPay(), order.getDispatFee()), parameter.getpDlJj()), 2));
						}else {
							orderInvoies.setTboiPtJj(Arith.round(Arith.mul(Arith.sub(order.getActualPay(), order.getDispatFee()), parameter.getpPtJj()), 2));
						}
					}
				    if (order.getDistributor()!=null) {
				    	Distributor distributor=Distributor.where.id(order.getDistributor()).get();
				    	if (distributor!=null) {
				    		DistributorIncome distributorIncome=DistributorIncome.where.directOrder(order.getId()).distributor(distributor.getId()).get();
				    		if (distributorIncome!=null&&distributorIncome.getOrderStatus()==(short)1) {
								orderInvoies.setTboiPsSy(Arith.round(Arith.mul(Arith.sub(order.getTotalSum(), order.getDispatFee()), parameter.getpPsYj()), 2));
											 Account tAccount=Account.where.member(distributor.getMember()).get();
											 if (tAccount!=null) {
												 tAccount.setMoney(Arith.round(Arith.add(tAccount.getMoney(), distributorIncome.getDistriIncome()), 2));//直接代理奖励
												 tAccount.update();
												 distributorIncome.setOrderStatus((short)2);
												 distributorIncome.update();
												 TbMsg msg=new TbMsg(
														 distributor.getMember()//会员
															 	,"您获得收益:"+distributorIncome.getDistriIncome()//内容
															 	,new Date()//时间
																);
														msg.save();
											}
											
								}
				    	  	
				    		BindingDistributor bindingDistributor=BindingDistributor.where.merchant(order.getMerchant()).distributor(distributor.getId()).get();
							if (bindingDistributor!=null&&bindingDistributor.getBindingdJxsh()!=null) {
								TbJxsh jxs=TbJxsh.where.tbjId(bindingDistributor.getBindingdJxsh()).get();
								if (jxs!=null) {
									order.setJxs(jxs.getTbjName());
									order.update();
								}
							 orderInvoies.setTboiJxsSy(((Arith.paytype(order.getTotalSum(), order.getDispatFee(), order.getDx(), parameter.getpPsYj(),order.getCouponFree()))*0.08)/0.18);
							List<OrderDetails> orderDetails=OrderDetails.where.orders(order.getId()).list(-1);
							List<Map<String, Object>> list=new ArrayList<Map<String,Object>>();
							for (OrderDetails orderDetails2 : orderDetails) {
								Map<String, Object> map=new HashMap<String, Object>();
								map.put("goodsNumber",orderDetails2.getGoodsNumber());
								map.put("name", orderDetails2.getName());
								map.put("price", orderDetails2.getPrice());
								map.put("number", orderDetails2.getNumber());
								map.put("status", orderDetails2.getStatus$());
								list.add(map);
							}
							 TbJxshIncome jxshIncome=new TbJxshIncome(
										order.getMerchant()
										,bindingDistributor.getBindingdJxsh()//经销商
										,order.getJxs()
									 	,order.getId()//订单编号
									 	,order.getAddTime()
										,order.getConsigneeName()
										,order.getDistributor$()
										,order.getOrderType()
										,JSON.toJSONString(list)
									 	,((Arith.paytype(order.getTotalSum(), order.getDispatFee(), order.getDx(), parameter.getpPsYj(),order.getCouponFree()))*0.08)/0.18//收益金额
									 	,new Date()
										);
								jxshIncome.save();
							}
				    	}
					}
				 TbPartners partners=TbPartners.where.tbpJiedao(order.getStreet()).get();
				 Region region=Region.where.id(order.getStreet()).get();
				 if (partners!=null) {
					 Member member2=Member.where.uid(partners.getTbpMember()).get();
					 orderInvoies.setTboiHhrSy(Arith.round(Arith.mul(Arith.sub(order.getTotalSum(), order.getDispatFee()), parameter.getpHhrYj()), 2));
					 TbPartnerIncome partnerIncome=new TbPartnerIncome(
							 order.getMerchant()//品牌
							 	,member2.getUid()//会员
							 	,order.getNo()
								,order.getOrderType()
							 	,member2.getNickName()
							 	,member.getHeader()//头像
							 	,member.getNickName()//昵称
							 	,region.getName()//街道
							 	,region.get$parent().getFullName()
							 	,new Date()//下单时间
							 	,Arith.round(Arith.mul(Arith.sub(order.getTotalSum(), order.getDispatFee()), parameter.getpHhrYj()), 2)//收益金额
							 );
					 partnerIncome.save();
				}
				 orderInvoies.setTboiSySy(Arith.round(Arith.sub(Arith.sub(Arith.sub(Arith.sub(Arith.sub(Arith.sub(Arith.sub(Arith.sub(Arith.sub(
						                                                         order.getTotalSum(), order.getDispatFee()),
						                                                         orderInvoies.getTboiPtSy()),
																				 orderInvoies.getTboiPtJj()),
																				 orderInvoies.getTboiPtZj()),
																				 orderInvoies.getTboiDlJj()),
																				 orderInvoies.getTboiDlZj()),
																				 orderInvoies.getTboiPsSy()),
																				 orderInvoies.getTboiHhrSy()),
																				 orderInvoies.getTboiJxsSy()), 2));
				orderInvoies.update(); 
		        protocol.set("type", 1);
		    	protocol.set("msg", "核销成功");
		    	return protocol;
			}
	}
}
